<template>
  <div>
    <el-input disabled :value="$route.query.roleName"></el-input>
    <el-tree
      style="margin: 20px 0"
      ref="treeRef"
      :data="userInfo"
      node-key="id"
      show-checkbox
      default-expand-all
      :props="defaultProps"
      @check-change="handleCheckChange"
    />
    <el-button :loading="loading" type="primary" @click="save">保存</el-button>
    <el-button  @click="cancel">取消</el-button>
  </div>
</template>

<script>
import permissionApi from "@/api/acl/permission";
export default {
  name: "RoleAuth",
  data() {
    return {
      userInfo: [],
      loading: false,
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  mounted() {
    this.obtainAListOfRoles()
  },
  methods:{
    //获取某个角色的权限列表
    async obtainAListOfRoles(){
      try {
        let resId = this.$route.query.id
        let result = await permissionApi.toAssign(resId)
        this.userInfo = result.data.children
        const checkedIds = this.getCheckedIds(this.userInfo);
        this.$refs.treeRef.setCheckedKeys(checkedIds);
      } catch (error) {
        console.log(error);
      }
    },
    handleCheckChange(data, checked, indeterminate) {
      //  console.log(this.$refs.tree.getCheckedNodes());
      // console.log(this.$refs.tree.getNode(node));
      //  console.log(this.$refs.tree.getCurrentKey());
    },
    getCheckedIds(auths, initArr = []) {
      auths.forEach((item) => {
        if (item.select && item.level === 4) {
          initArr.push(item.id);
        } else if (item.children) {
          this.getCheckedIds(item.children, initArr);
        }
      });
      return initArr;
    },
    save() {
      // 得到所有全选的id
      const checkedIds = this.$refs.treeRef.getCheckedKeys();
      // 得到所有半选的id
      const halfCheckedIds = this.$refs.treeRef.getHalfCheckedKeys();
      // 合并全选和半选的id， 并用逗号连接成串
      var ids = checkedIds?.concat(halfCheckedIds).join(",");

      this.loading = true;
      permissionApi.doAssign(this.$route.query.id, ids).then(async () => {
        this.loading = false;
        
        // 跳转到角色列表页面
        await this.$router.replace("/acl/role/list");
        // 跳转完成后, 如果分配的是当前用户角色的权限, 刷新一下浏览器
        const roleName = this.$route.query.roleName;
        
      });
    },
    cancel(){
      this.$router.replace('/acl/role/list') 
    }
  }
};
</script>

<style scoped>
</style>